/**
 * 文件上传指令
 * Created by lllllxt on  2017-04-21
 * last update by lllllxt on  2017-04-24
 *
 * 参数介绍：
 * fileIds : 文件id
 * fileModel={ 文件模型
 *     files : 当前文件信息
 *     removeIds : 待删除文件id数组
 * }
 * fileLength：文件个数 默认不限制
 *
 * isImg：是否图片 默认为false
 *      ----> isImg == true时才生效：
 *      isCircle：是否圆形 默认为false
 *      width：图片宽度 默认为150
 *      height：图片高度 默认为150
 *
 *      ----> isImg == false时才生效：
 *      btnName：上传按钮名称 默认为“上传文件”
 *
 * example :
 *  <div yg-file-upload
 data-file-ids="company.logoUrl"//abc 或者 'a','b','c'
 data-is-img="true"
 data-width="200"
 data-height="200"
 data-is-circle="true"
 data-file-length="1" readonly></div>
 *
 */
define(['app', 'js/services/FileResource', 'js/services/MessageBox'], function (app) {

    var deps = ['FileResource', 'MessageBox'];

    function directive (FileResource, MessageBox) {
        return {
            restrict: 'A',
            scope: {
                // fileModel: '=fileModel',
                fileIds: '=fileIds',
                fileLength: '@fileLength',
                btnName: '@btnName',
                isImg: '@isImg',
                isPdf: '@isPdf',
                isCircle: '@isCircle',
                width: '@width',
                height: '@height'
            },
            templateUrl: 'views/common/upload/fileUpload.html',
            replace: true,
            link: function (scope, element, attributes) {

                function obatinFileModelFiles () {
                    var files = [];
                    var filesIds = getFileIdsArray();
                    angular.forEach(filesIds, function (id, index) {
                        var fileVo = {
                            id: id
                        };
                        files.push(fileVo);
                    })
                    return files;
                }

                function getFileIdsArray () {
                    var array = new Array();
                    if (scope.fileIds) {
                        if (scope.fileLength == 1) {
                            array.push(scope.fileIds);
                        } else {
                            angular.forEach(scope.fileIds, function (id, index) {
                                array.push(id);
                            })
                        }
                    }
                    return array
                }

                function loadData (fileIds) {
                    scope.fileIds = fileIds;

                    scope.fileModel = {
                        files: obatinFileModelFiles(),
                        removeIds: []
                    };
                }

                loadData();

                //监听fileIds的变化赋予初始化的值
                scope.$watch('fileIds', function (newValue, oldValue) {
                    loadData(newValue);
                });


                scope.isImg = scope.isImg || false;
                scope.isPdf = scope.isPdf || false;
                scope.isEdit = !attributes.hasOwnProperty('readonly');

                if (scope.isImg) {
                    scope.isCircle = scope.isCircle || false;
                    scope.width = scope.width || 150;
                    scope.height = scope.height || 150;
                } else {
                    scope.btnName = scope.btnName || '上传文件';
                }

                // 上传
                element.bind('change', function (changeEvent) {
                    scope.$apply(function () {
                        //有选择文件才触发upload事件
                        if (changeEvent.target.files.length > 0) {
                            var file = changeEvent.target.files[0];
                            //上传图片时检查是否为图片
                            if (scope.isImg && file.type.indexOf("image/") < 0) {
                                MessageBox.error('文件格式不正确！只能上传（.jpg、.png、.gif、.tiff、.bmp、.dwg）格式结尾的文件');
                                return false;
                            }
                            if (scope.isPdf && file.type.indexOf("application/pdf") < 0) {
                                MessageBox.error('文件格式不正确！只能上传pdf文件');
                                return false;
                            }
                            if (file.size >= 52428800) {
                                MessageBox.error('文件过大！只能上传小于50M的文件');
                                return false;
                            }

                            FileResource.upload(file)
                            .success(function (data, header, config, status) {
                                if (data.state == 0) {
                                    var result = data.data;
                                    console.log('上传成功：');
                                    console.log(result);
                                    uploadSuccess(result);

                                } else {
                                    //TODO 清除file 的数据，让他可以重新选
                                    MessageBox.error('上传失败：' + data.message);
                                }
                            })
                            .error(function (data) {
                                MessageBox.error('连接服务器失败，请稍后再试');
                                console.log(data)
                            });
                        }
                    });

                });

                // 上传成功
                function uploadSuccess (data) {

                    var fileIds = getFileIdsArray();

                    var length = scope.fileLength || -1;

                    if (length == 1) {
                        // 更新fileModel
                        //上传成功后将原来的文件添加到删除列表
                        if (!(scope.fileModel.removeIds instanceof Array)) {
                            scope.fileModel.removeIds = [];
                        }
                        for (var j = 0; j < fileIds.length; j++) {
                            scope.fileModel.removeIds.push(fileIds[j]);
                        }
                        scope.fileModel.files = data;
                        // 更新fileIds
                        fileIds = [];
                        fileIds.push(data[0].id);
                    } else {
                        for (var i = 0; i < data.length; i++) {
                            // 更新fileModel
                            scope.fileModel.files.push(data[i]);
                            // 更新fileIds
                            fileIds.push(data[i].id);
                        }
                    }

                    if (length == 1) {
                        //如果只有一个 就去第一个的值
                        scope.fileIds = fileIds[0];
                    } else {
                        scope.fileIds = JSON.stringify(fileIds);
                    }


                    console.log(scope.fileModel.files)
                }

                // 删除
                scope.delFile = function (idx) {
                    if (scope.fileModel.files[idx] !== null) {
                        var deleteFid = scope.fileModel.files[idx].id;
                        MessageBox.confirm('确定要删除该附件吗？').result.then(function () {
                            if (!(scope.fileModel.removeIds instanceof Array)) {
                                scope.fileModel.removeIds = [];
                            }
                            // 更新fileModel
                            scope.fileModel.removeIds.push(deleteFid);
                            for (var i = 0; i < scope.fileModel.files.length; i++) {
                                if (scope.fileModel.files[i].id == deleteFid) {
                                    scope.fileModel.files.splice(i, 1);
                                    break;
                                }
                            }
                            // 更新fileIds
                            var fileIds = JSON.parse(scope.fileIds);
                            fileIds.removeItem(deleteFid);

                            scope.fileIds = JSON.stringify(fileIds);
                        });
                    } else {
                        scope.fileModel.files.splice(idx, 1);
                        var fileIds = JSON.parse(scope.fileIds);
                        fileIds.splice(idx, 1);
                        scope.fileIds = JSON.stringify(fileIds);
                    }
                    console.log(fileIds);
                    console.log(scope.fileModel.removeIds);
                }

                scope.getFile = function (fileId) {
                    return baseServices_restfulUrl + "/fileUpload/getFile.json?fileId=" + fileId;
                }
            }
        };
    }

    directive.$inject = deps;

    app.lazy.directive('ygFileUpload', directive);
});